package cn.kjcoder.orderServer.service.impl;

import cn.kjcoder.orderServer.Order;
import cn.kjcoder.orderServer.feign.ProductFeignApi;
import cn.kjcoder.orderServer.repository.OrderRepository;
import cn.kjcoder.orderServer.service.IOrderService;
import cn.kjcoder.productServer.domain.Product;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2021/12/21
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private ProductFeignApi productFeignApi;

    @Override
    public Order createOrder(Long userId, Long productId) {
        log.info("接收到{}号商品的下单请求,接下来调用商品微服务查询此商品信息", productId);


        /*List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        int count = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(count);
        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
        log.info(">>从nacos中获取到的微服务地址为:" + url);*/

        //Product product = restTemplate.getForObject("http://product-service/product/get?id=" + productId,Product.class);

        log.info("订单服务层调用");

        Product product = productFeignApi.findById(productId);

        log.info("查询到{}号商品的信息,内容是:{}", productId, JSON.toJSONString(product));
        Order order = new Order();
        order.setUid(userId);
        order.setUsername("hkj");
        order.setPid(productId);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        log.info("创建订单成功,订单信息为{}", JSON.toJSONString(order));
        return order;
    }
}
